<template>
  <section class="jdactivity-account-main">
    <section class="main-search merge">
      <span class="svg-container">
        <svg-icon icon-class="search"/>
      </span>
      <el-input v-model.trim="listQuery.activityName" placeholder="输入活动名称搜索" class="search-input"
                @keyup.enter.native="handleFilter"/>
      <section class="search-btn">
        <el-button class="filter-item" type="primary" @click="handleFilter">搜索</el-button>
        <el-button type="primary" @click="handleReset">重置</el-button>
      </section>
    </section>
    <section class="main-buttons">
      <section class="main-buttons-title">
        <span>京东活动</span>
      </section>
      <section class="main-buttons-btns">
        <el-button style="margin-left: 10px" @click="handleCreate">新建</el-button>
      </section>
    </section>

    <section class="main-table">
      <v-table :list="list" tag="jdactivitymain" :list-loading="listLoading" :filter-column="filtercolumn">
        <el-table-column label="操作" fixed="right" align="center" min-width="100" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="mini"
              @click="handlePublish(scope.row)"
            >{{ scope.row.status === "ZT01" ? "禁用" : "启用" }}
            </el-button
            >
            <el-button type="text" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
            <el-button type="text" size="mini" @click="handleDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </v-table>
      <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
                  @pagination="getList"/>
    </section>
    <el-dialog v-el-drag-dialog :destroy-on-close="true" :visible.sync="visible" :close-on-click-modal="false"
               title="新建/编辑京东活动" center width="750px">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="活动代码" prop="activityCode">
          <el-input :disabled="state!='create'" v-model.trim="form.activityCode" placeholder="请输入活动代码"/>
        </el-form-item>
        <el-form-item label="活动名称" prop="activityName">
          <el-input v-model.trim="form.activityName" placeholder="请输入活动名称"/>
        </el-form-item>
        <el-form-item label="起止时间" required>
          <el-col :span="8">
            <el-form-item label prop="startDate">
              <el-date-picker value-format="yyyy-MM-dd HH:mm:ss" type="datetime" placeholder="开始时间"
                              v-model="form.startDate" style="width: 100%;"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col class="line" :ofset="2" :span="1">-</el-col>
          <el-col :span="8">
            <el-form-item label prop="endDate">
              <el-date-picker value-format="yyyy-MM-dd HH:mm:ss" :disabled="notimelimit" type="datetime"
                              placeholder="结束时间" v-model="form.endDate" style="width: 100%;"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col class="line" :span="6">
            <el-checkbox v-model="notimelimit" @change="longTime">长期有效</el-checkbox>
          </el-col>
        </el-form-item>
        <el-form-item label="签名私钥" prop="rsaSignPrivateKey">
          <el-input type="textarea" :rows="4" v-model.trim="form.rsaSignPrivateKey" placeholder="请输入签名私钥"/>
        </el-form-item>

        <el-form-item label="加密公钥" prop="rsaEncryptPublicKey">
          <el-input type="textarea" :rows="4" v-model.trim="form.rsaEncryptPublicKey" placeholder="请输入加密公钥"/>
        </el-form-item>
        <el-form-item label="登录密钥" prop="loginAccessKey">
          <el-input v-model.trim="form.loginAccessKey" placeholder="请输入登录密钥"/>
        </el-form-item>

        <el-form-item label="接口密钥" prop="interfaceAccessKey">
          <el-input v-model.trim="form.interfaceAccessKey" placeholder="请输入接口密钥"/>
        </el-form-item>
        <el-form-item label="收银台地址" prop="collectMoneyAddress">
          <el-input v-model.trim="form.collectMoneyAddress" placeholder="请输入收银台地址"/>
        </el-form-item>
        <el-form-item label="访问地址" prop="visitAddress">
          <el-input v-model.trim="form.visitAddress" placeholder="请输入访问地址"/>
        </el-form-item>
        <el-form-item label="入金账户" prop="enterAccount">
          <el-select :disabled="state!='create'" v-model="form.enterAccount" placeholder="请选择" style="width: 100%"
                     @change="handleAccChange">
            <el-option v-for="(item, index) in accList" :key="index" :label="item.label" :value="item.value"/>
          </el-select>
        </el-form-item>
        <!-- 			<el-form-item label="充值记录" prop="depositRecord">
                <el-select :disabled="state!='create'" v-model="form.depositRecord" placeholder="请选择" style="width: 100%" >
                  <el-option v-for="(item, index) in rechList" :key="index" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
              <el-form-item  label="付款子账户" prop="childAccount">
                <el-select :disabled="state!='create'" v-model="form.childAccount" placeholder="请选择" style="width: 100%" @change="handleAccountChange">
                  <el-option v-for="(item, index) in accounts" :key="index" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="是否允许自有资金:" prop="ifAllowHaveMoney">
                <el-radio-group
                      :disabled="state === 'update'"
                      v-model.trim="form.ifAllowHaveMoney"
                      style="width: 100%;"
                    >
                      <el-radio label="1">是</el-radio>
                      <el-radio label="0">否</el-radio>
                </el-radio-group>
              </el-form-item> -->
        <!--     <el-form-item label="状态" prop="status">
               <el-radio-group v-model="form.status">
                 <el-radio label="ZT01">启用</el-radio>
                 <el-radio label="ZT02">禁用</el-radio>
               </el-radio-group>
             </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="default" style="padding: 10px 30px" @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="state === 'create'? createSubmit() : updateSubmit()">确 定</el-button>
      </div>
    </el-dialog>

  </section>
</template>
<script>
	import {
		del,
		queryPage,
		insert,
		update,
		getDictByCode,
		get,
		updateState,
		getAcc,
		getRechOne,
		getRech,
		queryCoupons,
		queryAccount,
		getInAcc
	} from './../api'
	import Pagination from '@/components/Pagination'
	import VTable from '@/components/Table'
	import elDragDialog from '@/directive/el-drag-dialog'
	import CryptoJS from '@/utils/aesJiaJM'

	export default {
		name: 'JdActivity',
		components: {VTable, Pagination},
		directives: {elDragDialog},
		data() {
			return {
				listQuery: {
					page: 1,
					limit: 10,
					activityName: ''
				},
				list: [],
				accList: [],
				rechList: [],
				accounts: [],
				total: 0,
				listLoading: false,
				visible: false,
				state: 'create',
				notimelimit: false,
				form: {
					id: '',
					activityCode: '',
					activityName: '',
					startDate: '',
					endDate: '',
					rsaSignPrivateKey: '',
					rsaEncryptPublicKey: '',
					loginAccessKey: '',
					interfaceAccessKey: '',
					collectMoneyAddress: '',
					visitAddress: '',
					status: '',
					enterAccount: '',
					// childAccount:'',
					// ifAllowHaveMoney:'',
					// depositRecord:''
				},
				rules: {
					activityCode: [{required: true, message: '请输入活动代码', trigger: 'blur'}],
					activityName: [{required: true, message: '请输入活动名称', trigger: 'blur'}],
					startDate: [{required: true, message: '请选择开始时间', trigger: 'blur'}],
					endDate: [{required: true, message: '请选择结束时间', trigger: 'blur'}],
					rsaSignPrivateKey: [{required: true, message: '请输入签名私钥', trigger: 'blur'}],
					rsaEncryptPublicKey: [{required: true, message: '请输入加密公钥', trigger: 'blur'}],
					loginAccessKey: [{required: true, message: '请输入登录密钥', trigger: 'blur'}],
					interfaceAccessKey: [{required: true, message: '请输入接口密钥', trigger: 'blur'}],
					collectMoneyAddress: [{required: true, message: '请输入收银台地址', trigger: 'blur'}],
					enterAccount: [{required: true, message: '请选择入金账户', trigger: 'change'}],
					visitAddress: [{required: true, message: '请输入访问地址', trigger: 'blur'}],
					// childAccount: [{ required: true, message: '请选择付款子账户', trigger: 'change' }],
					//     ifAllowHaveMoney: [{ required: true, message: '请选择是否允许自有资金', trigger: 'change' }],
					// status: [{ required: true, message: '请选择状态', trigger: 'change' }]
				},
				dict: {
					ACCOUNTTPYE: [] // 账户类型
				},
				yzFlag: true
			}
		},
		created() {
			this.getList()
			for (const key in this.dict) {
				this.getDict(key)
			}
		},
		methods: {
			longTime(val) {
				this.form.endDate = val ? '2099-12-31 23:59:59' : ''
				if (this.visible) {
					this.$refs.form.validateField('endDate');
				}
      },
			formatTime(str) {
				return str && str.replace(/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})$/, '$1-$2-$3 $4:$5:$6')
			},
			handleAccountChange(value) {
				const obj = this.accounts.find(a => a.subAcntTp === value)
				this.$alert(`您选择的付款子帐户是：${obj.subAcntNm}，状态为：${obj.subAcntSt == 1 ? '禁用' : '启用'}，
		    ${obj.subAcntStartTm ? '有效期是：' + this.formatTime(obj.subAcntStartTm) + '至' : ''}
		    ${obj.subAcntEndTm ? this.formatTime(obj.subAcntEndTm) + ']' : ''}`, '提示', {
					confirmButtonText: '确定'
				})
			},
			async handleAccChange(val) {
				// this.form.depositRecord=""
				// this.rechList= await this.getRechList(val)
			},
			getRechList(id) {
				const loading = this.$loading({
					lock: true,
					text: '请稍后',
					spinner: 'el-icon-loading',
					background: 'rgba(0, 0, 0, 0.3)'
				})
				return new Promise((resolve, reject) => {
					getRech({accountId: id}).then(res => {
						loading.close()
						const arr = res.data.data || []
						resolve(arr.map(a => ({
							...a,
							value: a.id,
							label: `${a.applyName}(${a.rechargeAmount}元)`
						})))
					}).catch(error => {
						loading.close()
						reject(error)
					})
				})
			},
			/**
			 * 启用/禁用
			 */
			handlePublish(row) {
				this.$confirm(row.status === 'ZT01' ? '确认禁用？' : '确认启用？', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					updateState({id: row.id, status: row.status === 'ZT01' ? 'ZT02' : 'ZT01'}).then(res => {
						if (res.data.code == '200') {
							this.$message({
								type: 'success',
								message: '操作成功!'
							});
							this.getList()
						}
					})
				}).catch(() => {

				});
			},
			getDict(code) {
				return new Promise((resolve, reject) => {
					getDictByCode(code).then(response => {
						this.dict[code] = response.data.data[0].list
					}).catch(error => {
						reject(error)
					})
				})
			},
			filtercolumn(scope, item) {
				if (item == 'rsaSignPrivateKey' || item == 'loginAccessKey') {
					return scope.row[item] ? CryptoJS.$aesJieM(scope.row[item]) : ''
				} else {
					return scope.row[item]
				}

			},

			handleReset() {
				this.listQuery.page = 1
				this.listQuery.activityName = ''

				this.getList()
			},

			handleFilter() {
				this.listQuery.page = 1
				this.getList()
			},
			randomString() {
				let chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
				let maxPos = chars.length
				let pwd = ''
				for (let i = 0; i < 32; i++) {
					pwd += chars.charAt(Math.floor(Math.random() * maxPos))
				}
				return pwd
			},
			async handleCreate() {
				for (const key in this.form) {
					if (key === 'status') {
						this.form[key] = 'ZT01'
					} else {
						this.form[key] = ''
					}
				}
				this.notimelimit = false
				this.accList = await this.getAccFun()
				this.state = 'create'
				this.visible = true
				// this.getAccounts().then((res) => {
				//   if (res.length > 0) {

				//     this.$nextTick(() => {
				//       this.$refs['form'].clearValidate()
				//     })
				//   } else {
				//     this.$message({
				//       title: '提示',
				//       message: '当前无可用付款子账户，请前往【福利中心--商户子账号管理】创建付款子账户。',
				//       type: 'error',
				//       duration: 2000
				//     })
				//   }
				// }).catch(err => {
				//   console.log(err)
				// })
			},
			getAccFun() {
				const loading = this.$loading({
					lock: true,
					text: '请稍后',
					spinner: 'el-icon-loading',
					background: 'rgba(0, 0, 0, 0.3)'
				})
				return new Promise((resolve, reject) => {
					getInAcc({accountStatus: 'ZHZT01'}).then(res => {
						loading.close()
						const arr = res.data.data || []
						resolve(arr.map(a => ({
							...a,
							value: a.id,
							label: `${a.name}(${CryptoJS.$aesJieM(a.accountNumber)})`
						})))
					}).catch(error => {
						loading.close()
						reject(error)
					})
				})
			},
			getAccounts() {
				const loading = this.$loading({
					lock: true,
					text: '请稍后',
					spinner: 'el-icon-loading',
					background: 'rgba(0, 0, 0, 0.3)'
				})
				return new Promise((resolve, reject) => {
					queryAccount({giveInfoId: this.form.id}).then(res => {
						loading.close()
						const arr = res.data.data || []
						this.accounts = arr.map(a => ({
							...a,
							value: a.subAcntTp,
							label: `${a.subAcntTp}-${a.subAcntNm}[${a.subAcntSt == 1 ? '禁用' : '启用'}]${a.subAcntStartTm ? '[' + this.formatTime(a.subAcntStartTm) + '至' : ''}${a.subAcntEndTm ? this.formatTime(a.subAcntEndTm) + ']' : ''}`
						}))
						resolve(arr)
					}).catch(error => {
						loading.close()
						reject(error)
					})
				})
			},
			async handleUpdate(row) {
				let ths = this
				this.accList = await this.getAccFun()
				this.getData(row.id).then(res => {
					for (const key in ths.form) {
						if (key == 'endDate') {
							this.notimelimit = res[key] == '2099-12-31 23:59:59'
						}
						this.form[key] = res[key]
					}
					console.log(this.form)
					// this.accList= this.getAccFun()
					ths.state = 'update'
					ths.visible = true
				}).catch(err => {
					ths.$message.error('获取详情失败')
				})
			},
			handleDelete(ids) {
				this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					const loading = this.$loading({
						lock: true,
						text: '请稍后',
						spinner: 'el-icon-loading',
						background: 'rgba(0, 0, 0, 0.3)'
					})
					return new Promise((resolve, reject) => {
						del(ids).then(() => {
							loading.close()
							this.$message({
								title: '成功',
								message: '删除成功',
								type: 'success',
								duration: 2000
							})
							this.getList()
						}).catch(error => {
							loading.close()
							reject(error)
						})
					})
				}).catch(() => {
				})
			},
			getData(id) {
				return new Promise((resolve, reject) => {
					get(id).then(res => {
						if (res.data.code == '200') {
							resolve(res.data.data)
						}
					}).catch(error => {
						reject(error)
					})
				})
			},
			/**
			 * 新增提交
			 */
			createSubmit() {
				this.$refs['form'].validate((valid) => {
					if (valid) {
						const loading = this.$loading({
							lock: true,
							text: '请稍后',
							spinner: 'el-icon-loading',
							background: 'rgba(0, 0, 0, 0.3)'
						})
						const params = Object.assign({}, this.form)
						// delete params.rsaEncryptPublicKey
						// delete params.interfaceAccessKey
						// params.rsaSignPrivateKey= CryptoJS.$aesJiaM(params.rsaSignPrivateKey)
						// params.loginAccessKey=params.loginAccessKey?CryptoJS.$aesJiaM(params.loginAccessKey) :params.loginAccessKey
						return new Promise((resolve, reject) => {
							insert(params).then(() => {
								this.dialogVisible = false
								loading.close()
								this.$message({
									title: '成功',
									message: '操作成功',
									type: 'success',
									duration: 2000
								})
								this.visible = false
								this.getList()
							}).catch(error => {
								loading.close()
								reject(error)
							})
						})
					} else {
						return false
					}
				})
			},
			/**
			 * 编辑提交
			 */
			updateSubmit() {
				this.$refs['form'].validate((valid) => {
					if (valid) {
						const loading = this.$loading({
							lock: true,
							text: '请稍后',
							spinner: 'el-icon-loading',
							background: 'rgba(0, 0, 0, 0.3)'
						})
						const params = Object.assign({}, this.form)
						// delete params.rsaEncryptPublicKey
						// delete params.interfaceAccessKey
						// params.rsaSignPrivateKey= CryptoJS.$aesJiaM(params.rsaSignPrivateKey)
						// params.loginAccessKey=params.loginAccessKey?CryptoJS.$aesJiaM(params.loginAccessKey) :params.loginAccessKey
						return new Promise((resolve, reject) => {
							update(params).then(() => {
								this.dialogVisible = false
								this.yzFlag = true
								loading.close()
								this.$message({
									title: '成功',
									message: '操作成功',
									type: 'success',
									duration: 2000
								})
								this.visible = false
								this.getList()
							}).catch(error => {
								loading.close()
								reject(error)
							})
						})
					} else {
						return false
					}
				})
			},
			getList(obj) {
				this.listLoading = true
				var query = {
					page: obj ? obj.page : this.listQuery.page,
					pageSize: obj ? obj.limit : this.listQuery.limit,
					activityName: this.listQuery.activityName
				}
				return new Promise((resolve, reject) => {
					queryPage(query).then(response => {
						this.list = response.data.data.rows || []
						this.total = response.data.data.total
						this.listLoading = false
					}).catch(error => {
						reject(error)
						this.listLoading = false
					})
				})
			}
		}
	}
</script>
<style lang="scss">
  @import '@/styles/mixin.scss';

  .jdactivity-account-main {
    padding: 10px;
    .el-dialog .el-dialog__body {
      max-height: 73vh !important;
    }
    .line {
      text-align: center;
    }
    .main-search {
      background-color: #fff;
      padding: 0 10px;
      .svg-container {
        padding: 0 5px 0 10px;
        color: #bfced6;
        vertical-align: middle;
        display: inline-block;
      }
      .search-input {
        width: 60%;
        position: relative;
        &:after {
          content: '';
          position: absolute;
          left: -25px;
          right: 0;
          bottom: 8px;
          height: 1px;
          background: rgba(226, 227, 232, 1);
        }
        input {
          outline: none;
          background: transparent;
          border: none;
          outline: medium;
          padding: 0;
          &:focus {
            outline: none;
            background-color: transparent;
          }
        }
      }
      .search-btn {
        display: inline-block;
        float: right;
        .el-button.is-round {
          padding: 10px 30px;
          margin-right: 34px;
        }
        .search-more {
          font-size: 14px;
          font-weight: 500;
          @include font-color($mainColor);
          cursor: pointer;
          margin-left: 10px;
        }
      }

      &.merge {
        height: 50px;
        line-height: 50px;
      }
    }

    .main-buttons {
      display: flex;
      line-height: 36px;
      margin-bottom: 10px;
      .main-buttons-title {
        flex: 1;
        height: 36px;
        line-height: 36px;
        font-size: 16px;
        font-weight: bold;
        color: rgba(51, 51, 51, 1);
        .num {
          @include font-color($mainColor);
        }
      }
    }
  }
</style>
